package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.DynamicConfigLab;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerRelationDepartmentDetail;
import com.isunland.managesystem.entity.CustomerRelationKeyDepartment.DepartMentList;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.SharedPreferencesUtil;
import java.util.HashMap;
import org.json.JSONException;

/**
 * 客户部门信息详情
 *
 * @author wu
 */
public class CustomerRelationDepartmentDetailFragment extends BaseFragment {

  public static final String EXTRA_DEPARTMENT = "com.isunland.managesystem.ui.extra_department";
  protected static final String TAG = CustomerRelationDepartmentDetailFragment.class.getName();
  private static final int REQUEST_DELETE = 3;
  private static final int REQUESUT_SUBMIT = 1;
  private static final int REQUESUT_ALTER = 0;
  private BaseVolleyActivity mActivity;
  //private TextView tvSuperDepartmen;// 上級部门
  private TextView tvDepartmentName;// 部门名称
  private TextView tvDepartmentDuty;// 部门职责说明
  private TextView tvDepartmentManager;// 部门经理
  private TextView tvDepartmentIndirectManager;// 部门主管领导
  private TextView tvDepartmentCreateTimeInfoCustomerRelation;// 部门创建时间
  private String departmentId;
  private String mStatus;

  public static Fragment newInstance(DepartMentList department) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_DEPARTMENT, department);
    CustomerRelationDepartmentDetailFragment fragment =
        new CustomerRelationDepartmentDetailFragment();
    fragment.setArguments(bundle);
    return fragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    super.onCreate(savedInstanceState);
    setTitleCustom(R.string.customerKeyDepartment1);
    mActivity = (BaseVolleyActivity) getActivity();
    mStatus = SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.DATA_STATUS, "");
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View view =
        inflater.inflate(R.layout.fragment_department_infor_customerrelation, container, false);
    //tvSuperDepartmen = (TextView) view.findViewById(R.id.tv_superDepartment_info_CustomerRelation);
    tvDepartmentName = (TextView) view.findViewById(R.id.tv_nameDepartment_info_CustomerRelation);
    tvDepartmentDuty = (TextView) view.findViewById(R.id.tv_dpartmentDuty_info_CustomerRelation);
    tvDepartmentManager =
        (TextView) view.findViewById(R.id.tv_dpartmentManager_info_CustomerRelation);
    tvDepartmentIndirectManager =
        (TextView) view.findViewById(R.id.tv_dpartmentIndirectManager_info_CustomerRelation);
    tvDepartmentCreateTimeInfoCustomerRelation =
        (TextView) view.findViewById(R.id.tv_dpartmentCreateTime_info_CustomerRelation);

    initView();
    // departmentDetailRuquest();

    DynamicConfigLab config =
        DynamicConfigLab.newInstance(mActivity, getString(R.string.module_deptColumns));
    config.autoConfigTitle(view);
    config.autoConfigVisiblity(view);
    return view;
  }

  private void initView() {
    String departmentName =
        SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.DEPARTMENT_NAME, "");
    departmentName = CustomerRelationDepartmentDetail.getDirectDepartment(departmentName);
    String departmentManager =
        SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.MANAGER_NAME, "");
    String directorManager =
        SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.DIRECTOR_NAME, "");
    String duty =
        SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.DUTYSCRIPT, "");
    departmentId =
        SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.DEPARTMENTID, "");
    String createTime =
        SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.REG_DATA, "");
    String mCustmerName =
        SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.CUSTOMER_NAME, "");
    LogUtil.i(TAG, "mCustmerName############" + mCustmerName);
    //String mPName = SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.PNAME, "");
    //
    //if (mPName != null) {
    //  tvSuperDepartmen.setText(mPName);
    //} else {
    //  tvSuperDepartmen.setText(mCustmerName);
    //}
    tvDepartmentName.setText(departmentName);
    tvDepartmentDuty.setText(duty);
    tvDepartmentManager.setText(departmentManager);
    tvDepartmentIndirectManager.setText(directorManager);
    tvDepartmentCreateTimeInfoCustomerRelation.setText(createTime);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    if (!("publish".equalsIgnoreCase(mStatus))) {
      inflater.inflate(R.menu.menu_department_edit, menu);
    } else {
      inflater.inflate(R.menu.menu_customerrelation_back, menu);
    }

    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {

    // 部门登记人Id
    String regStaffId =
        SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.PORGNAME, "");
    boolean isCreater = CurrentUser.newInstance(getActivity()).isCreater(regStaffId);

    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;

      case R.id.menu_item_alter:
        if (!isCreater) {// 不是创建人不允许更改操作。
          Toast.makeText(getActivity(), R.string.not_founder, Toast.LENGTH_SHORT).show();
          return true;
        } else {
          Intent intent =
              new Intent(getActivity(), CustomerRelationDepartmentInfoEditActivity.class);
          //intent.putExtra(CustomerRelationDepartmentInfoEditFragment.EXTRA_DATA, null);
          startActivityForResult(intent, 0);
        }
        break;

      case R.id.menu_item_delete:
        if (!isCreater) {// 不是创建人不允许更改操作。
          Toast.makeText(getActivity(), R.string.not_founder, Toast.LENGTH_SHORT).show();
          return true;
        } else {
          showDialog(REQUEST_DELETE);
        }
        break;

      case R.id.menu_item_confirm:
        if (!isCreater) {// 不是创建人不允许更改操作。
          Toast.makeText(getActivity(), R.string.not_founder, Toast.LENGTH_SHORT).show();
          return true;
        } else {
          showDialog(REQUESUT_SUBMIT);
          // }
        }
        break;
      case R.id.menu_item_back:
        if (!isCreater) {// 不是创建人不允许更改操作。
          Toast.makeText(getActivity(), R.string.not_founder, Toast.LENGTH_SHORT).show();
          return true;
        } else {
          submitCheck();
        }
        break;
      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  // 提交草稿状态和退回修改状态的部门
  private void submitCheck() {
    MyUtils.showDialogLoading(getActivity());
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DEARTMENT_CHECK);
    HashMap<String, String> depatementSub = new HashMap<>();
    depatementSub.put("ids", "'" + departmentId + "'");
    if ("publish".equalsIgnoreCase(mStatus)) {
      depatementSub.put("newDataStatus", "newback");
    } else {
      depatementSub.put("newDataStatus", "publish");
    }
    mActivity.volleyPost(url, depatementSub, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          MyUtils.dismissDialog();
          SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == success || null == success.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = success.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();

            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }

  private void showDialog(int type) {
    DialogFragment dialog;
    FragmentManager fm = getActivity().getSupportFragmentManager();
    switch (type) {

      case REQUEST_DELETE:
        dialog = BaseConfirmDialogFragment.newInstance(R.string.deleteConfirm);
        break;

      case REQUESUT_SUBMIT:
        dialog = BaseConfirmDialogFragment.newInstance(R.string.submitConfirm);
        break;
      default:
        return;
    }

    dialog.setTargetFragment(CustomerRelationDepartmentDetailFragment.this, type);
    dialog.show(fm, "");
  }

  private void volleyPostDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DEPARTMENT_DELETE);
    HashMap<String, String> params = new HashMap<>();
    departmentId =
        SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.DEPARTMENTID, null);
    params.put("ids", departmentId);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          MyUtils.dismissDialog();
          SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == success || null == success.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = success.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();

            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_DELETE) {
      volleyPostDelete();
    }
    if (requestCode == REQUESUT_ALTER) {
      getActivity().setResult(Activity.RESULT_OK);
      getActivity().finish();
    }
    if (requestCode == REQUESUT_SUBMIT) submitCheck();
    super.onActivityResult(requestCode, resultCode, data);
  }
}
